#include <tinx/user.h>
#include <tinx/debug.h>
#include <tinx/task.h>
#include <tinx/string.h>
#include <tinx/types.h>
#include <tinx/list.h>
#include <tinx/assert.h>

#define NR_USER 128

static user_t user_table[NR_USER];

static user_t *get_free_user()
{
    for (size_t i = 0; i < NR_USER; i++)
    {
        user_t *user = &user_table[i];
        if (user->uid == EOF)
        {
            user->uid = i;
            return user;
        }
    }
    panic("No more users!!!\n");
}

user_t *user_get(uid_t uid)
{
    assert(uid >= 0);
    user_t *user = &user_table[uid];
    if (user->uid == EOF)
    {
        user = NULL;
    }
    return user;
}

user_t *user_search(char *name)
{
    user_t *user = NULL;
    for (size_t i = 0; i < NR_USER; i++)
    {
        user_t *ptr = &user_table[i];
        if (strcmp(ptr->name, name) == 0)
        {
            user = ptr;
            break;
        }
    }
    return user;
}

int user_add_task(uid_t uid, task_t *task)
{
    user_t *user = user_get(uid);
    task->uid = uid;
    list_append(&user->tasks, &task->unode);
}

void user_remove_task(task_t *task)
{
    task->uid = -1;
    list_remove(&task->unode);
}

user_t *user_add(char *name, bool super)
{
    user_t *user = get_free_user();
    strncpy(user->name, name, USER_NAME_LEN);
    user->super = super;
    return user;
}

bool suser()
{
    task_t *task = running_task();
    uid_t uid = task->uid;
    user_t *user = user_get(uid);
    return user->super;
}

void user_init()
{
    // 初始化用户表
    for (size_t i = 0; i < NR_USER; i++)
    {
        user_t *user = &user_table[i];
        memset(user->name, 0, USER_NAME_LEN);
        list_init(&user->tasks);
        user->uid = EOF;
    }

    user_add("root", true);
    user_add("kernel", true);
}